package com.lgl.service.impl;

import com.google.gson.Gson;
import com.lgl.entity.ResponseResult;
import com.lgl.enums.AppHttpCodeEnum;
import com.lgl.exception.SystemException;
import com.lgl.service.UploadService;
import com.lgl.utils.PathUtils;
import com.lgl.utils.SecurityUtils;
import com.qiniu.common.QiniuException;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.Region;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Random;
import java.util.concurrent.TimeUnit;

@Data
@ConfigurationProperties(prefix = "oos")
@Service
public class UploadServiceImpl implements UploadService {
    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public ResponseResult uploadImg(MultipartFile img) {
        if (!img.getOriginalFilename().endsWith(".png") && !img.getOriginalFilename().endsWith(".jpg")) {
            throw new SystemException(AppHttpCodeEnum.FILE_TYPE_ERROR);
        }
        String url = oosUpload(img, img.getOriginalFilename());
        return ResponseResult.okResult(url);
    }

    @Override
    public void flushCode(String uuid, HttpServletRequest request, HttpServletResponse response) {

        try {
            createCode(uuid,request, response);
        } catch (IOException e) {
            throw new RuntimeException("验证码错误");
        }

    }

    private void createCode(String uuid, HttpServletRequest request, HttpServletResponse response) throws IOException {
        Random random = new Random();
//	            默认背景为黑色
        BufferedImage image = new BufferedImage(100, 50, BufferedImage.TYPE_INT_RGB);
//		获取画笔
        Graphics graphics = image.getGraphics();
//		默认填充为白色
        graphics.fillRect(0, 0, 100, 50);
//        验证码
        String yzm = "";
//	            验证码是由	数字 字母 干扰线 干扰点组成
//		文字素材
        String words = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890";
        char[] cs = words.toCharArray();
//		一般验证码为4位数
//      字母+数字
        for (int i = 0; i <= 3; i++) {
//			设置随机的颜色
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.setFont(new Font("微软雅黑", Font.BOLD, 30));
            char c = cs[random.nextInt(cs.length)];
            yzm = yzm + c;
            graphics.drawString(c + "", i * 20, 30);
        }
//		画干扰线
        int max = random.nextInt(10);
        for (int i = 0; i < max; i++) {
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.drawLine(random.nextInt(100), random.nextInt(50), random.nextInt(100), random.nextInt(50));
        }
//		画干扰点
        int max2 = random.nextInt(10);
        for (int i = 0; i < max2; i++) {
            graphics.setColor(new Color(random.nextInt(256), random.nextInt(256), random.nextInt(256)));
            graphics.drawOval(random.nextInt(80), random.nextInt(40), random.nextInt(5), random.nextInt(10));
        }
        response.setHeader("Cache-Control", "No-cache");
        //把验证码存到redis
        stringRedisTemplate.opsForValue().set("yzm:" + uuid, yzm.toLowerCase(), 60L, TimeUnit.SECONDS);
        ImageIO.write(image, "jpg", response.getOutputStream());
    }

    String accessKey;
    String secretKey;
    String bucket;

    public String oosUpload(MultipartFile img, String originalFilename) {
        //构造一个带指定 Region 对象的配置类
        Configuration cfg = new Configuration(Region.autoRegion());
        cfg.resumableUploadAPIVersion = Configuration.ResumableUploadAPIVersion.V2;// 指定分片上传版本
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String filePath = PathUtils.generateFilePath(originalFilename);
        String key = filePath;
        try {
            InputStream fileInputStream = img.getInputStream();
            Auth auth = Auth.create(accessKey, secretKey);
            String upToken = auth.uploadToken(bucket);
            try {
                Response response = uploadManager.put(fileInputStream, key, upToken, null, null);
                //解析上传成功的结果
                DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
                System.out.println(putRet.key);
                System.out.println(putRet.hash);
                return "http://rkjmyelu5.bkt.clouddn.com/" + putRet.key;
            } catch (QiniuException ex) {
                Response r = ex.response;
                System.err.println(r.toString());
                try {
                    System.err.println(r.bodyString());
                } catch (QiniuException ex2) {
                    //ignore
                }
            }
        } catch (Exception ex) {
            //ignore
        }
        return "aaa";
    }
}
